package com.spring.demo.publicutil.tree.entity;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.*;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author youjc
 * @date 2021年12月20日 10:14
 */
@Data
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class TreeNode {
    // 本节点
    private String id;
    // 父节点
    private String parent;
    // 叶 设置默认值为 false
    private Boolean leaf = false;
    // 子节点数据
    private List<TreeNode> children;
    // 名称
    private String num;
    // 名称
    private String key;
    /*   */

    /**
     * 递归封装树
     *
     * @param treeNodes 菜单
     * @param num       num
     * @param treeNodes 所有的
     */
    public static void recursionTreeNode(List<TreeNode> treeNodes, String num) {
        AtomicInteger i = new AtomicInteger(1);
        treeNodes.forEach(treeNode -> {
            if (StrUtil.isBlank(num)) {
                treeNode.setNum(i.toString());
            } else {
                treeNode.setNum(num + "-" + i.toString());
            }
            //遍历出子菜单
            if (CollUtil.isNotEmpty(treeNode.children)) {
                recursionTreeNode(treeNode.children, treeNode.num);
            }
            i.getAndIncrement();
        });
    }


    /**
     * 递归封装树
     *
     * @param newTreeNodes 一级菜单
     * @param num          num
     * @param treeNodes    所有的
     */
    public static void recursionTreeNode(List<TreeNode> newTreeNodes, List<TreeNode> treeNodes, String num) {
        AtomicInteger i = new AtomicInteger(1);
        newTreeNodes.forEach(treeNode -> {
            if (StrUtil.isBlank(num)) {
                treeNode.setNum(i.toString());
            } else {
                treeNode.setNum(num + "-" + i.toString());
            }
            //遍历出子菜单
            List<TreeNode> treeNodes1 = treeNodes.stream().filter(v -> v.getParent().equals(treeNode.getKey())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(treeNodes1)) {
                treeNode.setChildren(treeNodes1);
                recursionTreeNode(treeNodes1, treeNodes, treeNode.num);
            }
            i.getAndIncrement();
        });
    }
}
